package com.imax.center.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imax.center.annotation.NoAuth;
import com.imax.center.common.Result;
import com.imax.center.common.ResultCode;
import com.imax.center.entity.SensorEventData;
import com.imax.center.service.*;
import com.imax.center.utils.TcpDataUtil;
import com.imax.center.websocket.WsEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import com.imax.center.service.impl.h3yun.H3yunOperate;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import com.imax.center.utils.MyFileUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Api(tags = "测试接口")
@RestController
@RequestMapping("/api")
public class TestController {
    
    @Autowired
    MinioService minioService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DeviceDataService deviceDataService;

    @Autowired
    SensorEventDataService sensorEventDataService;

    @Autowired
    H3yunOperate h3yunOperate;

    @Autowired
    WsEndpoint wsEndpoint;

    @Autowired
    CommonService commonService;

    @Autowired
    H3yunService h3yunService;

    @ApiOperation(value = "测试文件上传到minio", notes = "测试文件上传到minio")
    @PostMapping("/uploadToMinio")
    public Result<String> uploadToMinio(@RequestParam("file") MultipartFile file) throws Exception {
        String filePath = minioService.upload(file);
        return Result.success(filePath);
    }

    @NoAuth
    @ApiOperation(value = "测试文件URL上传且绘制元素", notes = "测试文件URL上传且绘制元素")
    @PostMapping("/testUrlUploadAndDrawEle")
    public Result<String> testUrlUploadAndDrawEle(@RequestParam("filePath") String filePath, @RequestParam("fileName") String fileName, @RequestParam("str") String str) throws IOException {
        MultipartFile multipartFile = MyFileUtils.urlToMultipartFile(filePath);
        //将str转为JSONObject
        JSONObject map = JSONObject.parseObject(str);
        String path = commonService.saveImageDrawEle(multipartFile, map, fileName);
        return Result.success(path);
    }

    @ApiOperation(value = "测试文件URL上传接口", notes = "测试文件URL上传接口")
    @PostMapping("/testUrlUpload")
    //文件上传参数设置
    public Result<String> testUrlUpload(
        @RequestParam("schemaCode") String schemaCode,
        @RequestParam("filePropertyName") String filePropertyName,
        @RequestParam("bizObjectId") String bizObjectId,
        @RequestParam("filePath") String filePath
    ) throws IOException {
        // 将filePath转换为MultipartFile
        MultipartFile multipartFile = MyFileUtils.urlToMultipartFile(filePath);
        
        // 上传文件到氚云
        String attachmentId = h3yunOperate.uploadAttachment(schemaCode, filePropertyName, bizObjectId, multipartFile);
        return Result.success(attachmentId);
    }

    @ApiOperation(value = "测试附件上传接口", notes = "测试附件上传接口")
    @PostMapping("/testFileUpload")
    //文件上传参数设置
    public Result<String> testFileUpload2(
        @RequestParam("schemaCode") String schemaCode,
        @RequestParam("filePropertyName") String filePropertyName,
        @RequestParam("bizObjectId") String bizObjectId,
        @RequestParam("file") MultipartFile file
    ) throws IOException {
        String attachmentId = h3yunOperate.uploadAttachment(schemaCode, filePropertyName, bizObjectId, file);
        return Result.success(attachmentId);
    }

    @ApiOperation(value = "测试接口", notes = "需要token验证的测试接口")
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("Hello IMAX!", "测试成功");
    }

    @ApiOperation(value = "测试TCP报文")
    @GetMapping("/testTcpMsg")
    public Result<String> testTcpMsg(String message, String pwd) {
        if (pwd == null || !pwd.equals("Abcd@1234")) {
            return Result.error(ResultCode.SYSTEM_ERROR, "密码错误");
        }
        Map<String, Object> data = TcpDataUtil.parseData(message);
        deviceDataService.syncHandlerEvent(message, data);
        return Result.success("ok", "测试成功");
    }

    @GetMapping("/sendMsgByWs")
    @Operation(summary = "sendMsgByWs", description = "sendMsgByWs")
    public Result<String> sendMsgByWs(String msg) {
        wsEndpoint.sendMessageToAllUser(msg);
        return Result.success("ok");
    }

    @GetMapping("/no-token")
    @Operation(summary = "不需要token验证的接口")
    @NoAuth
    public Result<String> noToken() {
        return Result.success("Hello, 这个接口不需要token验证！");
    }

    @GetMapping("/http-get")
    public Result<JSONObject> testHttpGet() {
        String response = restTemplate.getForObject(
            "https://api.luobenxi.top/api/test",
            String.class
        );
        
        JSONObject jsonResponse = JSONObject.parseObject(response);
        log.info("GET请求响应结果: {}", jsonResponse);

        return Result.success(jsonResponse);
    }

    @PostMapping("/http-post")
    public Result<JSONArray> testHttpPost() {
        JSONObject param = new JSONObject();
        param.put("timestamp", System.currentTimeMillis());
        
        try {
            String response = restTemplate.postForObject(
                "https://api.luobenxi.top/api/getTasks",
                param,
                String.class
            );
            
            JSONObject jsonResponse = JSONObject.parseObject(response);
            log.info("POST请求响应结果: {}", jsonResponse);
            
            if (jsonResponse != null && "0".equals(jsonResponse.getString("code"))) {
                JSONArray data = jsonResponse.getJSONArray("data");
                return Result.success(data, jsonResponse.getString("message"));
            } else {
                String errorMsg = jsonResponse != null ? jsonResponse.getString("message") : "请求失败";
                log.error("POST请求失败: {}", errorMsg);
                return Result.error(ResultCode.SYSTEM_ERROR, errorMsg);
            }
        } catch (Exception e) {
            log.error("POST请求异常: ", e);
            return Result.error(ResultCode.SYSTEM_ERROR, "系统异常");
        }
    }

    @GetMapping("/querySensorEventDataPage")
    public Result<IPage<SensorEventData>> querySensorEventDataPage(Integer pageNo, Integer pageSize, String cn) {
        Page<SensorEventData> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SensorEventData> queryWrapper = new LambdaQueryWrapper<>();
        if (cn != null && !Objects.equals(cn, "")) {
            queryWrapper.eq(SensorEventData::getCn, cn);
        }
        queryWrapper.orderByDesc(SensorEventData::getCreateTime);
        IPage<SensorEventData> pageData = sensorEventDataService.page(page, queryWrapper);
        return Result.success(pageData);
    }

    @PostMapping("/addSensorEventData")
    public Result<Boolean> addSensorEventData(@RequestBody SensorEventData sensorEventData) {
        sensorEventData.setCreateTime(LocalDateTime.now());
        boolean save = sensorEventDataService.save(sensorEventData);
        return Result.success(save);
    }

    @ApiOperation(value = "统计昨日各医院污水处理量", notes = "统计昨日各医院污水处理量")
    @GetMapping("/statYesterdayW00000Count")
    public Result<JSONArray> statYesterdayW00000Count() {
        return h3yunService.getYesterdayW00000Count();
    }

    @ApiOperation(value = "写入昨日各医院污水处理量", notes = "写入昨日各医院污水处理量")
    @GetMapping("/addYesterdayW00000Count")
    public Result<String> addYesterdayW00000Count(String pwd) {
        if (pwd == null || !pwd.equals("Abcd@1234")) {
            return Result.error(ResultCode.SYSTEM_ERROR, "密码错误");
        }
        Result<JSONArray> result = h3yunService.getYesterdayW00000Count();
        return h3yunService.addYesterdayW00000Count(result.getData());
    }

    @ApiOperation(value = "预警事件删除图片测试", notes = "预警事件删除图片测试")
    @GetMapping("/queryEventTempPicAndDelete")
    public Result<String> queryEventTempPicAndDelete() {
        h3yunService.queryEventTempPicAndDelete();
        return Result.success("ok");
    }

    @ApiOperation(value = "测试删除文件", notes = "根据文件路径删除文件，支持相对路径和绝对路径")
    @GetMapping("/testDeleteFile")
    public Result<Boolean> testDeleteFile(String filePath) {
        try {
            boolean result = commonService.deleteFile(filePath);
            if (result) {
                return Result.success(true, "文件删除成功");
            } else {
                return Result.success(false, "文件不存在或删除失败");
            }
        } catch (Exception e) {
            log.error("删除文件测试异常: {}", filePath, e);
            return Result.error(ResultCode.SYSTEM_ERROR, "删除文件时发生异常: " + e.getMessage());
        }
    }

    @ApiOperation(value = "获取默认图片上传目录下所有文件名", notes = "获取默认图片上传目录下所有文件名")
    @GetMapping("/listAllImageFiles")
    public Result<List<String>> listAllImageFiles() {
        try {
            List<String> result = commonService.listAllImageFiles();
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ResultCode.SYSTEM_ERROR, "发生异常: " + e.getMessage());
        }
    }

    @ApiOperation(value = "测试删除目录下所有文件", notes = "测试删除目录下所有文件")
    @GetMapping("/queryAndBatchDelEventPicTest")
    public Result<String> queryAndBatchDelEventPicTest() {
        try {
            h3yunService.queryAndBatchDelEventPicTest();
            return Result.success("ok");
        } catch (Exception e) {
            return Result.error(ResultCode.SYSTEM_ERROR, "发生异常: " + e.getMessage());
        }
    }

} 